//职员管理

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Button, Table, Modal, Row, Upload, Icon, DatePicker, Select, Pagination} from 'antd';
import {project, coupon} from '../value';
import '../css/other.css';
import moment from 'moment';
import {config} from "../config";
import {AddRedPackets, EditRedPackets} from '../components/operateManage';

import {EditorState, convertToRaw, ContentState} from 'draft-js';
import {Editor} from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class RedPacket extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchData: {},
            pagination: {current: 1, pageSize: 10, total: 0},
            data: [],
            currentPageSize: 0,
            pageCount: 0,
            imgUrl: '',
        }
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'order_number',
        },
        {
            title: '活动名',
            dataIndex: 'coupon_name',
        },
        {
            title: '使用条件',
            dataIndex: 'coupon_condition'
        },
        {
            title: '金额',
            dataIndex: 'coupon_price'
        },
        {
            title: '数量',
            dataIndex: 'coupon_count'
        },
        {
            title: '剩余数量',
            dataIndex: 'coupon_leave'
        },
        {
            title: '开始结束时间',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>{moment(data.coupon_startTime).format('YYYY-MM-DD')}至{moment(data.coupon_endTime).format('YYYY-MM-DD')}</span>
                )
            }
        },
        {
            title: '创建时间',
            dataIndex: 'coupon_createTime',
            render: coupon_createTime => {
                return (
                    <span>{moment(coupon_createTime).format('YYYY-MM-DD')}</span>
                )
            }
        },
        {
            title: '状态',
            dataIndex: 'coupon_status',
            render: coupon_status => {
                let text = '';
                if (coupon_status === '1') {
                    text = '未开始';
                } else if (coupon_status === '2') {
                    text = '进行中';
                } else if (coupon_status === '3') {
                    text = '已结束';
                } else if (coupon_status === '4') {
                    text = '已停用';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <div>
                        <EditRedPackets id={data.coupon_id}
                                        refresh={() => this.handleRefreshAfterUpdate()}></EditRedPackets>
                        {
                            data.coupon_isable === '1' ? <Button style={{marginLeft: '10px'}} type="danger"
                                                                 onClick={() => this.handleChangeStatus(data.coupon_id, 0)}>停用</Button> :
                                <Button style={{marginLeft: '10px'}} type="primary"
                                        onClick={() => this.handleChangeStatus(data.coupon_id, 1)}>启用</Button>
                        }
                        <Button style={{marginLeft: '10px'}} type="danger"
                                onClick={() => this.handleChangeStatus(data.coupon_id, 2)}>删除</Button>
                    </div>
                )
            }
        },
    ];

    render() {
        const rowSelection = {
            // 表格中复选框发生变化时
            onChange: (selectedRowKeys, selectedRows) => {
                let positionId = [];
                let positionName = [];
                positionId = selectedRowKeys;
                selectedRows.forEach((item) => {
                    positionName.push(item.role_name);
                });
                console.log(selectedRowKeys);
                this.setState({
                    positionId: positionId,  //批量选中的职位ID
                    positionName: positionName,
                    selectCount: selectedRowKeys.length, //一共选择的职位数量
                })
            },

        };
        const {pagination, currentPageSize, pageCount} = this.state;
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    邀请奖励
                </div>
                <div style={{marginTop: 10}}>
                    <AddRedPackets refresh={() => this.handleRefreshAfterCreate()}></AddRedPackets>
                </div>
                <SearchLists refresh={() => this.handleRefreshAfterCreate()}
                             clickSearch={(values) => this.handleGetValue(values)}/>
                <div style={{fontSize: 12, marginBottom: 20, marginTop: 20}}>
                    当前第<span style={{color: 'red'}}>{pagination.current}</span>页, 当前页共<span
                    style={{color: 'red'}}>{currentPageSize}</span>条数据，一共<span
                    style={{color: 'red'}}>{pagination.total}</span>条数据
                </div>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={(record, index) => index}
                        dataSource={this.state.data}
                        loading={this.state.loading}
                        pagination={false}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <Row style={{textAlign: 'right', marginTop: 20}}>
                    <Pagination {...this.state.pagination} showSizeChanger showQuickJumper
                                onChange={(page, pageSize) => this.handleOnChange(page, pageSize)}
                                onShowSizeChange={(current, size) => this.handleOnShowSizeChange(current, size)}/>
                </Row>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        const param = {
            page: 1,
            size: 10
        };
        this.searchCouponList(param);
    }

    /**
     * 获取搜索条件
     */
    handleGetValue(value) {
        let end_time1 = '', end_time2 = '', start_time1 = '', start_time2 = '';
        const {status, start_time, end_time} = value;
        if (start_time && start_time.length > 0) {
            start_time1 = moment(start_time[0]._d).format('YYYY-MM-DD');
            start_time2 = moment(start_time[1]._d).format('YYYY-MM-DD');
        }
        if (end_time && end_time.length > 0) {
            end_time1 = moment(end_time[0]._d).format('YYYY-MM-DD');
            end_time2 = moment(end_time[1]._d).format('YYYY-MM-DD');
        }
        const searchData = {
            statusSearch: status,
            startTime1: start_time1,
            endTime1: end_time1,
            startTime2: start_time2,
            endTime2: end_time2
        };
        this.setState({searchData});
        const param = {
            page: 1,
            size: 10,
            ...searchData
        };
        this.searchCouponList(param);
    }

    /**
     * 处理创建后刷新事件
     */
    handleRefreshAfterCreate() {
        const {searchData} = this.state;
        const param = {
            page: 1,
            size: 10,
            ...searchData
        };
        this.searchCouponList(param);
    }

    /**
     * 处理删除后刷新事件
     */
    handleRefreshAfterDelete() {
        const {searchData} = this.state;
        const param = {
            page:1,
            size:10,
            ...searchData
        };
        this.searchCouponList(param);
    }

    /**
     * 处理更新后刷新事件
     */
    handleRefreshAfterUpdate() {
        const {searchData,pagination} = this.state;
        const param = {
            page:pagination.current,
            size:pagination.pageSize,
            ...searchData
        };
        this.searchCouponList(param);
    }

    /**
     * 处理页码、显示数量变化事件
     * @param pagination
     * @param filters
     * @param sorter
     */
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.setState({pagination: pagination1});
    };

    /**
     * 处理页码改变事件
     * @param page
     * @param pageSize
     */
    handleOnChange(page, pageSize) {
        let {searchData} = this.state;
        let param = {
            page,
            size: pageSize,
            ...searchData
        };
        this.searchCouponList(param);
    }

    /**
     * 处理pageSize变化回调
     * @param current
     * @param size
     */
    handleOnShowSizeChange(current, size) {
        let {searchData} = this.state;
        let param = {
            page: current,
            size: size,
            ...searchData
        };
        this.searchCouponList(param);
    }

    /**
     * 查找红包列表
     * @param param
     */
    searchCouponList(param) {
        let _this = this;
        _this.setState({loading: true});
        app.post(coupon.SEARCH_COUPON_LIST, param).then(result => {
            if (result.code === 1) {
                const data = result.data;
                for (let i = 0; i < data.length; i++) {
                    data[i].order_number = i + 1;
                }
                const pagination = {total: result.count, current: param.page, pageSize: param.size};
                this.setState({pagination, data: data, loading: false, currentPageSize: data.length});
            } else {
                app.alert(result.msg, 'success', 1);
                const pagination = {total: 0, current: 0, pageSize: 0};
                this.setState({pagination, data: [], loading: false, currentPageSize: 0});
            }
        });
    }

    /**
     * 启用和停用红包
     * @param id
     * @param type
     */
    handleChangeStatus(id, type) {
        let _this = this;
        if (type === 2) {
            confirm({
                content: '您确定要删除该红包吗？',
                onOk() {
                    app.post(coupon.UPDATE_COUPON_ISABLE, {coupon_id: id, coupon_isable: '2'}).then((req) => {
                        if (req.code === 1) {
                            app.alert("删除成功", 'success', 1);
                            _this.handleRefreshAfterDelete();
                        } else {
                            app.alert(req.msg, 'error', 1);
                        }
                    })
                },
                onCancel() {
                },
            });
        } else if (type === 0) {
            confirm({
                content: '您确定要停用该红包吗？',
                onOk() {
                    app.post(coupon.UPDATE_COUPON_ISABLE, {coupon_id: id, coupon_isable: '0'}).then((req) => {
                        if (req.code === 1) {
                            app.alert("停用成功", 'success', 1);
                            _this.handleRefreshAfterUpdate();
                        } else {
                            app.alert(req.msg, 'error', 1);
                        }
                    })
                },
                onCancel() {
                },
            });
        } else if (type === 1) {
            app.post(coupon.UPDATE_COUPON_ISABLE, {coupon_id: id, coupon_isable: '1'}).then((req) => {
                if (req.code === 1) {
                    app.alert("启用成功", 'success', 1);
                    _this.handleRefreshAfterUpdate();
                } else {
                    app.alert(req.msg, 'error', 1);
                }
            })
        }
    }
}


class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            project_name: '',
            start_time: [],
            end_time: [],
            typeList: [
                {
                    id: '01',
                    name: '会员注册奖励'
                }
            ]
        }
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const dateFormat = 'YYYY-MM-DD';
        return (
            <div style={{display: 'flex', marginTop: 20, marginBottom: 5}}>
                <div style={{display: 'flex', width: '310px', height: '28px'}}>
                    <div style={{width: 80, height: 28, lineHeight: '28px', color: '#000000'}}>开始时间：</div>
                    <RangePicker format={dateFormat} style={{width: 210}} onChange={(e) => this.handleStartTime(e)}/>
                </div>
                <div style={{display: 'flex', width: '310px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 80, height: 28, lineHeight: '28px', color: '#000000'}}>结束时间：</div>
                    <RangePicker format={dateFormat} style={{width: 210}} onChange={(e) => this.handleEndTime(e)}/>
                </div>
                <div style={{display: 'flex', width: '170px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 60, height: 28, lineHeight: '28px', color: '#000000'}}>状态：</div>
                    <Select style={{width: 110}} placeholder={'请选择状态'} onChange={(e) => this.handleType(e)}>
                        <Option value="1">未开始</Option>
                        <Option value="2">进行中</Option>
                        <Option value="3">已结束</Option>
                        <Option value="4">已停用</Option>
                    </Select>
                </div>
                <div style={{display: 'flex', width: '120px', height: '28px', marginLeft: 20}}>
                    <Button type="primary" onClick={() => this.handleSearchComplain1()}>搜索</Button>
                </div>
            </div>
        )
    };

    componentDidMount() {
    };

    /**
     * 处理开始时间变化事件
     * @param e
     */
    handleStartTime(e) {
        this.setState({start_time: e});
        this.handleSearchComplain({key: 'start_time', value: e});
    }

    /**
     * 处理结束时间变化事件
     * @param e
     */
    handleEndTime(e) {
        this.setState({end_time: e});
        this.handleSearchComplain({key: 'end_time', value: e});
    }

    /**
     * 状态选择变化事件
     * @param e
     */
    handleType(e) {
        this.setState({status: e});
        this.handleSearchComplain({key: 'status', value: e});
    }

    handleSearchComplain(param) {
        let {status, start_time, end_time} = this.state;
        if (param.key === 'status') {
            status = param.value;
        }
        if (param.key === 'start_time') {
            start_time = param.value;
        }
        if (param.key === 'end_time') {
            end_time = param.value;
        }
        let data = {
            status,
            start_time,
            end_time
        };
        this.props.clickSearch(data);
    };

    handleSearchComplain1() {
        let {status, start_time, end_time} = this.state;
        let data = {
            status,
            start_time,
            end_time
        };
        this.props.clickSearch(data);
    }
}

const SearchLists = Form.create()(SearchList);
const RedPackets = Form.create()(RedPacket);

export default RedPackets


